// Cookie
function getCookie(cname) {
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i].trim();
		var arrC = c.split("=");
		if (arrC[0] == cname) {
			return arrC[1];
		}
	}
	return "";
}

$(document).ready(function() {
	//获取cookie
	var json = getCookie('cart');
	//json=>数组
	var cart = JSON.parse(json);
	var html = '';

	cart.forEach(function(item) {
		//模板字符串
		html += `
		<div class="container w list-heade item-box clearfix">
			<div class="t-check fl">
				<input id="input1" class="J-checkbox" type="checkbox">
				<label for="input1"></label>
			</div>
			<div class="car-img fl">
				<img src="${item.photo}" width="50">
			</div>
			<div class="car-name fl size">${item.name}</div>
			<div class="car-price fl price-size">${item.price}</div>
			<div class="car-num fl pri">
				<div class="change-goods-num clearfix">
					<a href="javascript:;" class="J_minus fl">-</a>
					<span class="goods-num fl">${item.num}</span>
					<a href="javascript:;" class="J_plus fl">+</a>
				</div>
			</div>
			<div class="car-total fl totals">599</div>
			<div class="car-action fl iconfont"><a class="add"  href="javascript:;" title="删除">&#xe668; </a></div>
		</div>`
	});
	$('.list-body').html(html);




	// 购物车逻辑
	// 全选单选
	$('#input').change(function() {
		// console.log($(this).prop('checked'));
		$('.J-checkbox').prop('checked', $(this).prop('checked'));
		app();
	});
	$('.J-checkbox').change(function() {
		if ($('.J-checkbox:checked').length == $('.J-checkbox').length) {
			$('#input').prop('checked', true);
		} else {
			$('#input').prop('checked', false);
		}
		app();
	});
	// 加
	$('.J_plus').click(function() {
		var price = parseFloat($('.price-size').text());
		var num = parseFloat($('.goods-num').text());	
		num++;
		$('.goods-num').text(num);
		$('.totals').text(num * price);
		// app();
		// $('.js').text(num);
	});
	// 减
	$('.J_minus').click(function() {
		var price = $('.price-size').text();
		var num = $('.goods-num').text();
		if (num > 1) {
			num--;
		}
		$('.goods-num').text(num);
		$('.totals').text(num * price);
		// app();
		// $('.js').text(num);
	});
	function app(){
		var num = parseFloat($('.goods-num').text());
		var pricesum = 0;
		var rmb = parseFloat($('.totals').text());
		console.log(rmb);
		$('#input1:checked').each(function() {
			pricesum += rmb;
			$('.js').text(num);
		});
		$('.em').text(pricesum);
	}
	app();
	$('#input1').click(function () {
		app();
		var num = parseFloat($('.goods-num').text());
		// $('.js').text(num);
	});
	
	// 删除选择购物车
	$('.add').click(function() {
		$(this).parents('.item-box').remove();
	})





});
